<script setup>
import { ref } from 'vue'
import { articleClassficationAddService, articleClassficationEditService } from '@/api/article'
const isComfirm = ref(false) // 是否弹出确认框
const formModel = ref({}) // 表单数据
const formRef = ref() // 用于表单校验的整个表单对象
const emit = defineEmits(['submitSuccess'])
// 确认框打开
const open = (obj) => {
  formModel.value = { ...obj }
  isComfirm.value = true
  // console.log(formModel.value.id)
}
// 表单校验规则
const rules = {
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur'},
    { pattern: /^\S{1,10}$/, message: '请输入1到10位的非空分类名称', trigger: 'blur' }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { pattern: /^[0-9a-zA-Z]{1,10}$/, message: '请输入1到10位的数字或字母' }
  ]
}
// 提交添加文章分类
const submitArt = async () => {
  // 表单校验
  await formRef.value.validate()
  // 表单提交
  if (formModel.id) {
    await articleClassficationEditService(formModel.value)
  }else {
    await articleClassficationAddService(formModel.value)
  }
  ElMessage.success('添加成功')
  emit('submitSuccess')
  isComfirm.value = false
}
// 暴露方法使父组件激活此组件
defineExpose({
  open
})

</script>

<template>
  <el-dialog
    v-model="isComfirm"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form :model="formModel" :rules=rules ref="formRef">
      <el-form-item prop="cate_name" label="分类名称" label-width="100" style="padding-right:50px">
        <el-input placeholder="请输入分类名称" v-model="formModel.cate_name"></el-input>
      </el-form-item>
      <el-form-item prop="cate_alias" label="分类别名" label-width="100" style="padding-right:50px">
        <el-input placeholder="请输入分类别名" v-model="formModel.cate_alias"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isComfirm = false">取消</el-button>
        <el-button type="primary" @click="submitArt">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>

</style>